﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using SmartSpace.Core;
using System.IO;

namespace SmartSpace.Packaging
{
    public class XUserUtil
    {
        public static List<User> Load(string filePath)
        {
            XDocument xDoc = XDocument.Load(filePath);
            List<User> users = new List<User>();
            IEnumerable<XElement> elements = xDoc.Root.Elements("user");
            foreach (var item in elements)
            {
                User user = new User();
                user.Id = new Guid(item.Attribute("id").Value);
                user.Account = item.Attribute("account").Value;
                user.Name = item.Attribute("name").Value;
                user.Email = item.Attribute("email").Value;
                user.Telphone = item.Attribute("phone").Value;
                user.CreatedTime = DateTime.Now;
                user.Password = "123456";
                users.Add(user);
            }
            return users;
        }

        public static List<User> Load(Stream stream)
        {
            XDocument xDoc = XDocument.Load(stream);
            List<User> users = new List<User>();
            IEnumerable<XElement> elements = xDoc.Root.Elements("user");
            foreach (var item in elements)
            {
                User user = new User();
                user.Id = new Guid(item.Attribute("id").Value);
                user.Account = item.Attribute("account").Value;
                user.Name = item.Attribute("name").Value;
                user.Email = item.Attribute("email").Value;
                user.Telphone = item.Attribute("phone").Value;
                user.CreatedTime = DateTime.Now;
                user.Password = "123456";
                users.Add(user);
            }
            return users;
        }

        public static bool Save(List<User> users, string filePath)
        {
            XDocument xDoc = new XDocument();
            xDoc.Add(new XElement("users"));
            foreach (var item in users)
            {
                xDoc.Root.Add(new XElement("user",
                    new XAttribute("id", item.Id),
                    new XAttribute("account", item.Account),
                    new XAttribute("name", item.Name),
                    new XAttribute("email", item.Email),
                    new XAttribute("phone", item.Telphone)));
            }
            xDoc.Save(filePath);
            return true;
        }
    }
}
